#include "xs_def.h"
#include "xs_log.h"
#include "xs_pipe.h"

/* Read characters from the pipe and echo them to @code{stdout}.  */

size_t read_from_pipe (int file, char *messbuff, int len)
{

    FILE *stream;
    int c, t = 0;

    if(messbuff == NULL) return (size_t)EXIT_FAILURE;

    stream = fdopen(file, "r");
    if(stream == NULL){
        xs_logd("fdopen pipe error!");
        return EXIT_FAILURE;
    }

    while((c = fgetc (stream)) != EOF)
    {
        //putchar(c);
        messbuff[t++] = c;
        if(len > t) continue;
        else break; /* Have no enough sapce to store message */
    }

    fclose(stream);
    return t;
}

/* Write some random text to the pipe. */
size_t write_to_pipe (int file, const char *message, size_t len)
{
    FILE *stream;
    size_t t = 0;

    if(message == NULL) return (size_t)EXIT_FAILURE;

    stream = fdopen (file, "w");
    if(stream == NULL){
        xs_logd("fdopen pipe error!");
        return EXIT_FAILURE;
    }
    while(t != len)
        t += fprintf (stream, message);

    fclose (stream);

    return t;
}
